package com.digitalchina.lxnsy.activity.old;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.NonNull;
import android.view.View;
import android.widget.DatePicker;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.apkfuns.logutils.LogUtils;
import com.bigkoo.pickerview.OptionsPickerView;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.api.BusinessAccount;
import com.digitalchina.lxnsy.api.BusinessExpert;
import com.digitalchina.lxnsy.api.BusinessFile;
import com.digitalchina.lxnsy.api.BusinessPayPassword;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.entity.ExpertTitleVO;
import com.digitalchina.lxnsy.entity.FileVO;
import com.digitalchina.lxnsy.entity.OrganizationVO;
import com.digitalchina.lxnsy.loader.GlideImageLoader;
import com.digitalchina.lxnsy.toolkit.ActivityTaskManager;
import com.digitalchina.lxnsy.toolkit.CustomDialog;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.FrescoUtil;
import com.digitalchina.lxnsy.toolkit.GotoUtil;
import com.digitalchina.lxnsy.toolkit.SharedPreferencesUtil;
import com.digitalchina.lxnsy.toolkit.StringUtil;
import com.digitalchina.lxnsy.xml.ChannelXML;
import com.digitalchina.lxnsy.xml.ExpertInfoXML;
import com.digitalchina.lxnsy.xml.PersonalInfoXML;
import com.digitalchina.lxnsy.xml.RongCloudXML;
import com.digitalchina.lxnsy.xml.UserXML;
import com.facebook.drawee.view.SimpleDraweeView;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.lzy.okhttputils.model.HttpParams;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Set;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import chihane.jdaddressselector.BottomDialog;
import chihane.jdaddressselector.OnAddressSelectedListener;
import chihane.jdaddressselector.model.City;
import chihane.jdaddressselector.model.County;
import chihane.jdaddressselector.model.Province;
import chihane.jdaddressselector.model.Street;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

import static com.digitalchina.lxnsy.activity.old.AccountPersonManagementActivity.REQUEST_CODE_EDIT;
import static com.digitalchina.lxnsy.constant.MSG.MSG_FILE_UPLOAD_SUCCESS;
import static com.digitalchina.lxnsy.constant.MSG.MSG_SAVE_EXPERT_INFO_SUCCESS;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：
 * 包名：com.digitalchina.bigdata.activity
 * 创建人：郑皓
 * 创建时间：2017/7/20 14:24
 * 修改备注：
 * ================================================
 */
public class AccountExpertManagementActivity extends BaseActivity {

    @Bind(R.id.iv_expert_avatar)
    SimpleDraweeView ivExpertAvatar;
    @Bind(R.id.tv_expert_user_name)
    TextView tvExpertUserName;
    @Bind(R.id.tv_expert_sex)
    TextView tvExpertSex;
    @Bind(R.id.tv_expert_company)
    TextView tvExpertCompany;
    @Bind(R.id.tv_expert_address)
    TextView tvExpertAddress;
    @Bind(R.id.tv_expert_address_detail)
    TextView tvExpertAddressDetail;
    @Bind(R.id.tv_expert_achievement)
    TextView tvExpertAchievement;
    @Bind(R.id.tv_expert_intro)
    TextView tvExpertIntro;
    @Bind(R.id.tv_expert_area)
    TextView tvExpertArea;
    @Bind(R.id.tv_expert_authentication)
    TextView tvExpertAuthentication;
    @Bind(R.id.tv_expert_mobile_phone)
    TextView tvExpertMobilePhone;

    @Bind(R.id.tv_expert_true_name)
    TextView tvExpertTrueName; // 真实姓名
    @Bind(R.id.tv_expert_title)
    TextView tvExpertTitle;  // 专家职称
    @Bind(R.id.tv_expert_title_number)
    TextView tvExpertTitleNumber;  // 证书编号
    @Bind(R.id.iv_expert_title_photo)
    SimpleDraweeView ivExpertTitlePhoto;  // 证书照片
    @Bind(R.id.progress_bar_percent)
    ProgressBar progressBarPercent;
    @Bind(R.id.tv_percent)
    TextView tvPercent;
    @Bind(R.id.tv_expert_company_other)
    TextView tvExpertCompanyOther;
    @Bind(R.id.rl_expert_company_other)
    RelativeLayout rlExpertCompanyOther;
    @Bind(R.id.tv_expert_birthday)
    TextView tvExpertBirthday;

    private int msgWhat;
    private String mKey, mValue;
    // 图片
    public static final int REQUEST_CODE_SELECT = 100;
    private ArrayList<ImageItem> selectedImageList = new ArrayList<>(); //当前选择的所有图片
    private String filePath = ""; // 图片地址
    // 性别选择器
    private OptionsPickerView pvSex;
    private OptionsPickerView pvOrganization;
    private List<String> sexVOList = new ArrayList<>();

    // 区域code
    private String provinceCode = "";
    private String cityCode = "";
    private String countyCode = "";
    // 分类和领域
    private String expertAreaTypeCode = "";
    private String expertAreaDirectionCode = "";
    private int fileType = -1;  // 0-头像 1-职称照片 2-身份证照片
    // 专家职称List
    private List<ExpertTitleVO> expertTitleVOList = new ArrayList<>();
    // 专家职称选择器
    private OptionsPickerView pvExpertTitle;
    // 专家职称code
    private String expertTitleId = "";

    private int mYear, mMonth, mDayOfMonth;//年月日

    @Override
    public void setLayout() {
        setContentLayout(R.layout.activity_account_expert_management);
        setTitle("账户管理");
    }

    @Override
    public void initMember() {

        // 获取工作单位
        BusinessAccount.organizationList(this, mHandler);

        tvExpertUserName.setText(UserXML.getUseraccName(AccountExpertManagementActivity.this));

        // 优先加载本地数据
        setTextViewForXML();

        initSexData();
    }

    @Override
    protected void onResume() {
        super.onResume();

        // 手机号码取userXML
//        String pStrMobile = UserXML.getMobilePhone(AccountExpertManagementActivity.this);
//        tvExpertMobilePhone.setText(pStrMobile.replaceAll("(?<=[\\d]{3})\\d(?=[\\d]{4})", "*"));
    }

    /**
     * 加载本地数据
     */
    private void setTextViewForXML() {
        FrescoUtil.showImageSmall(ExpertInfoXML.getPhoto(this), ivExpertAvatar);
        tvExpertSex.setText(ExpertInfoXML.getExpertSex(this));

        tvExpertAddress.setText(ExpertInfoXML.getAddress(this));
        tvExpertAddressDetail.setText(ExpertInfoXML.getAddressDetail(this));
        tvExpertAchievement.setText(ExpertInfoXML.getAchievement(this));
        tvExpertIntro.setText(ExpertInfoXML.getExpertIntroduce(this));
        tvExpertArea.setText(ExpertInfoXML.getExpertClassification(this));

        // 新增
        tvExpertTrueName.setText(ExpertInfoXML.getExpertName(this));
        tvExpertTitle.setText(ExpertInfoXML.getExpertTitleName(this));
        tvExpertTitleNumber.setText(ExpertInfoXML.getExpertTitleNum(this));
        FrescoUtil.showImageSmall(ExpertInfoXML.getExpertTitleImage(this), ivExpertTitlePhoto);

        // 工作单位
        tvExpertCompany.setText(ExpertInfoXML.getOrganizationName(this));
        if (ExpertInfoXML.getOrganizationName(this).equals("其他")) {
            rlExpertCompanyOther.setVisibility(View.VISIBLE);
            tvExpertCompanyOther.setText(ExpertInfoXML.getOtherAddress(this));
        }

        tvExpertBirthday.setText(ExpertInfoXML.getBirthday(this));
        setProgressBarPercent();
    }

    /**
     * 设置进度条数据
     */
    private void setProgressBarPercent() {
        List<TextView> textViewList = new ArrayList<>(); // 填写字段的textView
        int sum = 12; // 需要维护字段的总数
        int writeNum = 0; // 当前已经维护的字段
        if (!StringUtil.isStrEmpty(ExpertInfoXML.getPhoto(this)))
            writeNum++;
        if (!StringUtil.isStrEmpty(ExpertInfoXML.getExpertTitleImage(this)))
            writeNum++;

        textViewList.add(tvExpertUserName); // 用户名 必填
        textViewList.add(tvExpertSex);
        textViewList.add(tvExpertCompany);
        textViewList.add(tvExpertAddress);
//        textViewList.add(tvExpertAddressDetail);
//        textViewList.add(tvExpertAchievement);
        textViewList.add(tvExpertIntro);
        textViewList.add(tvExpertArea);
        textViewList.add(tvExpertTrueName);
        textViewList.add(tvExpertTitle);
        textViewList.add(tvExpertTitleNumber);
        textViewList.add(tvExpertBirthday);

        for (int i = 0; i < textViewList.size(); i++) {
            if (!StringUtil.isTextEmpty(textViewList.get(i)))
                writeNum++;
        }

        double percent = (double) writeNum / sum * 100;
        progressBarPercent.setProgress((int) percent);
        tvPercent.setText((int) percent + "%");

    }

    @Override
    public void addListener() {

    }

    /**
     * 性别选择器
     */
    private void initSexData() {

        sexVOList.add("男");
        sexVOList.add("女");

        pvSex = new OptionsPickerView.Builder(AccountExpertManagementActivity.this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                String select = sexVOList.get(options1);
                tvExpertSex.setText(select);
                saveExpertInfoBase(editExpert("expertSex", select));
            }
        })
                .setSubCalSize(16)//确定取消按钮大小
                .setLineSpacingMultiplier(1.5f) //设置两横线之间的间隔倍数（范围：1.2 - 2.0倍 文字高度）
                .setDividerColor(getResources().getColor(R.color.colorFontLightGrayB))//设置分割线的颜色
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(18)//设置滚轮文字大小
                .setSelectOptions(0)  //设置默认选中项
                .build();

        pvSex.setPicker(sexVOList);
    }

    /**
     * 工作单位选择器
     *
     * @param list
     */
    private void initOrganization(final List<OrganizationVO> list) {


        pvOrganization = new OptionsPickerView.Builder(AccountExpertManagementActivity.this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                String select = list.get(options1).getPickerViewText();
                tvExpertCompany.setText(select);
                tvExpertCompanyOther.setText("");
                ExpertInfoXML.setOtherAddress(AccountExpertManagementActivity.this, "");
                if (select.equals("其他")) {
                    rlExpertCompanyOther.setVisibility(View.VISIBLE);
                } else {
                    rlExpertCompanyOther.setVisibility(View.GONE);
                }

                saveExpertInfoBase(editExpert("organizationId", list.get(options1).getId()));

            }
        })
                .setSubCalSize(16)//确定取消按钮大小
                .setLineSpacingMultiplier(1.5f) //设置两横线之间的间隔倍数（范围：1.2 - 2.0倍 文字高度）
                .setDividerColor(getResources().getColor(R.color.colorFontLightGrayB))//设置分割线的颜色
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(18)//设置滚轮文字大小
                .setSelectOptions(0)  //设置默认选中项
                .build();

        pvOrganization.setPicker(list);
    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                dismissDialog();
                msgWhat = msg.what;
                switch (msgWhat) {
                    case MSG_FILE_UPLOAD_SUCCESS:  // 上传图片
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_FILE_UPLOAD_FIELD:
                        showToast(msg.obj.toString());
                        break;
                    case MSG_SAVE_EXPERT_INFO_SUCCESS:  // 修改专家基础信息
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_SAVE_EXPERT_INFO_FIELD:
                        showToast(msg.obj.toString());
                        break;
                    case MSG.MSG_EXPERT_TITLE_LIST_SUCCESS: // 获取专家职称接口
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_ORGANIZATION_LIST_SUCCESS: // 工作地址
                        List<OrganizationVO> organizationVOList = FastJsonUtil.getListBean(msg.obj.toString(), "list", OrganizationVO.class);
                        if (organizationVOList != null) {
                            for (int i = 0; i < organizationVOList.size(); i++) {
                                if (organizationVOList.get(i) == null || organizationVOList.get(i).getPickerViewText() == null) {
                                    organizationVOList.remove(i);
                                    i--;
                                }
                            }
                            initOrganization(organizationVOList);
                        }
                        break;
                    case MSG.MSG_EXPERT_TITLE_LIST_FIELD:
                        showToast(msg.obj.toString());
                        break;
                    case MSG.MSG_HAVE_PAY_PASSWORD_SUCCESS: // 查询用户是否设置支付密码
                        String havePayPassword = FastJsonUtil.getString(msg.obj.toString(), "havePayPassword");
                        if ("0".equals(havePayPassword)) {
                            new MaterialDialog.Builder(AccountExpertManagementActivity.this)
                                    .title("提示")
                                    .content("您还没有设置过提现密码，是否现在设置？")
                                    .positiveText("去设置")
                                    .negativeText("取消")
                                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                                        @Override
                                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                            GotoUtil.gotoActivity(AccountExpertManagementActivity.this, SetPayPasswordOneActivity.class,"type",0);
                                        }
                                    })
                                    .show();
                        } else
                            GotoUtil.gotoActivity(AccountExpertManagementActivity.this, AmendPayPasswordActivity.class);
                        break;
                    case MSG.MSG_HAVE_PAY_PASSWORD_FIELD:
                        showToast(msg.obj.toString());
                        break;
                }
            }
        };
    }

    @Override
    public void callBack(Object object) {
        switch (msgWhat) {
            case MSG_FILE_UPLOAD_SUCCESS:  // 上传图片成功后 返回FileName
                FileVO fileVO = FastJsonUtil.getBean(object.toString(), "body", "fileStorage", FileVO.class);
                if (fileVO == null)
                    return;

                switch (fileType) {
                    case 0:
                        FrescoUtil.showImageSmall(fileVO.getName(), ivExpertAvatar);
                        saveExpertInfoBase(editExpert("photo", fileVO.getName()));
                        break;
                    case 1:
                        FrescoUtil.showImageSmall(fileVO.getName(), ivExpertTitlePhoto);
                        saveExpertInfoBase(editExpert("expertTitleImage", fileVO.getName()));
                        break;
                }
//                FrescoUtil.showImageSmall(fileVO.getName(), ivExpertAvatar);
//                saveExpertInfoBase(editExpert("photo", fileVO.getName()));
                break;
            case MSG_SAVE_EXPERT_INFO_SUCCESS:  // 修改专家基础信息
                saveToXML();
                break;
            case MSG.MSG_EXPERT_TITLE_LIST_SUCCESS: // 获取专家职称接口
                expertTitleVOList = FastJsonUtil.getListBean(object.toString(), "titleList", ExpertTitleVO.class);
                if (expertTitleVOList != null && expertTitleVOList.size() > 0) {
                    initExpertTitleData();
                    pvExpertTitle.show();
                } else
                    showToast("获取专家职称失败");
                break;
        }
    }


    /**
     * 专家职称选择器
     */
    private void initExpertTitleData() {


        pvExpertTitle = new OptionsPickerView.Builder(AccountExpertManagementActivity.this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                String select = expertTitleVOList.get(options1).getPickerViewText();
                expertTitleId = expertTitleVOList.get(options1).getId();
                saveExpertInfoBase(expertTitle("expertTitleId", select));
            }
        })
                .setSubCalSize(16)//确定取消按钮大小
                .setLineSpacingMultiplier(1.5f) //设置两横线之间的间隔倍数（范围：1.2 - 2.0倍 文字高度）
                .setDividerColor(getResources().getColor(R.color.colorFontLightGrayB))//设置分割线的颜色
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(18)//设置滚轮文字大小
                .setSelectOptions(0)  //设置默认选中项
                .build();

        pvExpertTitle.setPicker(expertTitleVOList);
    }

    /**
     * 上传信息后保存到XML
     */
    private void saveToXML() {
        switch (mKey) {
            case "photo":
                ExpertInfoXML.setPhoto(this, mValue);
                break;
            case "trueName":
                ExpertInfoXML.setExpertName(this, mValue);
                break;
            case "expertTitleId": // 专家职称修改
                ExpertInfoXML.setExpertTitleName(this, mValue);
                ExpertInfoXML.setExpertTitleCode(this, expertTitleId);
                break;
            case "titleNumber": // 专家职称号
                ExpertInfoXML.setExpertTitleNum(this, mValue);
                break;
            case "expertTitleImage":
                ExpertInfoXML.setExpertTitleImage(this, mValue);
                break;
            case "expertSex":
                ExpertInfoXML.setExpertSex(this, mValue);
                break;
            case "otherAddress":
                ExpertInfoXML.setOtherAddress(this, mValue);
                break;
            case "address":
                ExpertInfoXML.setAddress(this, mValue);
                ExpertInfoXML.setProvinceCode(this, provinceCode);
                ExpertInfoXML.setCityCode(this, cityCode);
                ExpertInfoXML.setCountyCodeCode(this, countyCode);
                break;
            case "addressDetail":
                ExpertInfoXML.setAddressDetail(this, mValue);
                break;
            case "achievement":
                ExpertInfoXML.setAchievement(this, mValue);
                break;
            case "expertIntroduce":
                ExpertInfoXML.setExpertIntroduce(this, mValue);
                break;
            case "birthday":
                ExpertInfoXML.setBirthday(this, mValue);
                break;
            case "area":
                ExpertInfoXML.setExpertAreaType(this, expertAreaTypeCode);
                ExpertInfoXML.setExpertAreaDirection(this, expertAreaDirectionCode);
                ExpertInfoXML.setExpertClassification(this, mValue);
                break;
            case "organizationId":
                ExpertInfoXML.setOrganizationID(this, mValue);
                ExpertInfoXML.setOrganizationName(this, tvExpertCompany.getText().toString());
                break;
        }

        setTextViewForXML();

    }


    private void saveExpertInfoBase(HttpParams params) {
        BusinessExpert.saveExpertInfoBase(this, params, mHandler);
    }


    /**
     * 组装数据
     *
     * @param key
     * @param value
     * @return
     */
    private HttpParams editExpert(String key, String value) {

        showDialog("请稍候...");

        mKey = key;
        mValue = value;
        HttpParams params = new HttpParams();
        params.put("photo", key.equals("photo") ? value : ExpertInfoXML.getPhoto(this));
        params.put("expertSex", key.equals("expertSex") ? value : ExpertInfoXML.getExpertSex(this));
        params.put("workUnit", key.equals("workUnit") ? value : ExpertInfoXML.getWorkUnit(this));
//        params.put("addressDetail", key.equals("addressDetail") ? value : ExpertInfoXML.getAddressDetail(this));
//        params.put("achievement", key.equals("achievement") ? value : ExpertInfoXML.getAchievement(this));
        params.put("expertIntroduce", key.equals("expertIntroduce") ? value : ExpertInfoXML.getExpertIntroduce(this));
        params.put("expertAreaTypeCode", ExpertInfoXML.getExpertAreaType(this));
        params.put("expertAreaDirectionCode", ExpertInfoXML.getExpertAreaDirection(this));
        params.put("provinceCode", ExpertInfoXML.getProvinceCode(this));
        params.put("cityCode", ExpertInfoXML.getCityCode(this));
        params.put("countyCode", ExpertInfoXML.getCountyCode(this));

        // 新增参数
        params.put("expertName", key.equals("trueName") ? value : ExpertInfoXML.getExpertName(this));
        params.put("expertTitleId", key.equals("expertTitleId") ? value : ExpertInfoXML.getExpertTitleCode(this));
        params.put("expertTitleNum", key.equals("titleNumber") ? value : ExpertInfoXML.getExpertTitleNum(this));
        params.put("expertTitleImage", key.equals("expertTitleImage") ? value : ExpertInfoXML.getExpertTitleImage(this));

        // 工作单位
        params.put("organizationId", key.equals("organizationId") ? value : ExpertInfoXML.getOrganizationID(this)); // 工作单位Id
        params.put("otherAddress", key.equals("otherAddress") ? value : ExpertInfoXML.getOtherAddress(this)); // 其他地址

        params.put("birthday", key.equals("birthday") ? value : ExpertInfoXML.getBirthday(this)); // 生日

        return params;
    }

    /**
     * 修改领域
     *
     * @param key
     * @param value
     * @return
     */
    private HttpParams editArea(String key, String value) {

        showDialog("请稍候...");

        mKey = key;
        mValue = value;
        HttpParams params = new HttpParams();

        params.put("photo", ExpertInfoXML.getPhoto(this));
        params.put("expertSex", ExpertInfoXML.getExpertSex(this));
        params.put("workUnit", ExpertInfoXML.getWorkUnit(this));
//        params.put("addressDetail", ExpertInfoXML.getAddressDetail(this));
//        params.put("achievement", ExpertInfoXML.getAchievement(this));
        params.put("expertIntroduce", ExpertInfoXML.getExpertIntroduce(this));
        // 三级分类和领域
        params.put("expertAreaTypeCode", expertAreaTypeCode);
        params.put("expertAreaDirectionCode", expertAreaDirectionCode);

        params.put("provinceCode", ExpertInfoXML.getProvinceCode(this));
        params.put("cityCode", ExpertInfoXML.getCityCode(this));
        params.put("countyCode", ExpertInfoXML.getCountyCode(this));

        // 新增参数
        params.put("expertName", ExpertInfoXML.getExpertName(this));
        params.put("expertTitleId", ExpertInfoXML.getExpertTitleCode(this));
        params.put("expertTitleNum", ExpertInfoXML.getExpertTitleNum(this));
        params.put("expertTitleImage", ExpertInfoXML.getExpertTitleImage(this));

        // 工作单位
        params.put("organizationId", ExpertInfoXML.getOrganizationID(this)); // 工作单位Id
        params.put("otherAddress", ExpertInfoXML.getOtherAddress(this)); // 其他地址

        params.put("birthday", ExpertInfoXML.getBirthday(this)); // 生日

        return params;
    }

    /**
     * 修改地址
     *
     * @param key
     * @param value
     * @return
     */
    private HttpParams editAddress(String key, String value) {

        showDialog("请稍候...");

        mKey = key;
        mValue = value;
        HttpParams params = new HttpParams();
        params.put("photo", ExpertInfoXML.getPhoto(this));
        params.put("expertSex", ExpertInfoXML.getExpertSex(this));
        params.put("workUnit", ExpertInfoXML.getWorkUnit(this));
//        params.put("addressDetail", ExpertInfoXML.getAddressDetail(this));
//        params.put("achievement", ExpertInfoXML.getAchievement(this));
        params.put("expertIntroduce", ExpertInfoXML.getExpertIntroduce(this));
        params.put("expertAreaTypeCode", ExpertInfoXML.getExpertAreaType(this));
        params.put("expertAreaDirectionCode", ExpertInfoXML.getExpertAreaDirection(this));
        params.put("provinceCode", provinceCode);
        params.put("cityCode", cityCode);
        params.put("countyCode", countyCode);

        // 新增参数
        params.put("expertName", ExpertInfoXML.getExpertName(this));
        params.put("expertTitleId", ExpertInfoXML.getExpertTitleCode(this));
        params.put("expertTitleNum", ExpertInfoXML.getExpertTitleNum(this));
        params.put("expertTitleImage", ExpertInfoXML.getExpertTitleImage(this));

        // 工作单位
        params.put("organizationId", ExpertInfoXML.getOrganizationID(this)); // 工作单位Id
        params.put("otherAddress", ExpertInfoXML.getOtherAddress(this)); // 其他地址

        params.put("birthday", ExpertInfoXML.getBirthday(this)); // 生日

        return params;
    }

    /**
     * 修改职称
     *
     * @param key
     * @param value
     * @return
     */
    private HttpParams expertTitle(String key, String value) {

        showDialog("请稍候...");

        mKey = key;
        mValue = value;
        HttpParams params = new HttpParams();
        params.put("photo", ExpertInfoXML.getPhoto(this));
        params.put("expertSex", ExpertInfoXML.getExpertSex(this));
        params.put("workUnit", ExpertInfoXML.getWorkUnit(this));
//        params.put("addressDetail", ExpertInfoXML.getAddressDetail(this));
//        params.put("achievement", ExpertInfoXML.getAchievement(this));
        params.put("expertIntroduce", ExpertInfoXML.getExpertIntroduce(this));
        params.put("expertAreaTypeCode", ExpertInfoXML.getExpertAreaType(this));
        params.put("expertAreaDirectionCode", ExpertInfoXML.getExpertAreaDirection(this));
        params.put("provinceCode", ExpertInfoXML.getProvinceCode(this));
        params.put("cityCode", ExpertInfoXML.getCityCode(this));
        params.put("countyCode", ExpertInfoXML.getCountyCode(this));

        // 新增参数
        params.put("expertName", ExpertInfoXML.getExpertName(this));
        params.put("expertTitleId", expertTitleId);
        params.put("expertTitleNum", ExpertInfoXML.getExpertTitleNum(this));
        params.put("expertTitleImage", ExpertInfoXML.getExpertTitleImage(this));

        params.put("birthday", ExpertInfoXML.getBirthday(this)); // 生日

        return params;
    }

    @Override
    public void rightOnClick() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    /**
     * 修改头像跳转至自定义相册
     */
    private void selectImage(int fileType) {
        this.fileType = fileType;
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);  //显示拍照按钮
        imagePicker.setSelectLimit(1);    //选中数量限制
        imagePicker.setMultiMode(false);    //是否多选模式
        if (fileType == 0) {
            imagePicker.setCrop(true);        //允许裁剪（单选才有效）
            imagePicker.setSaveRectangle(true); //是否按矩形区域保存
            imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
            imagePicker.setFocusWidth(380);   //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
            imagePicker.setFocusHeight(380);  //裁剪框的高度。单位像素（圆形自动取宽高最小值）
            imagePicker.setOutPutX(400);//保存文件的宽度。单位像素
            imagePicker.setOutPutY(400);//保存文件的高度。单位像素
        } else
            imagePicker.setCrop(false);
        Intent intent = new Intent(AccountExpertManagementActivity.this, ImageGridActivity.class);
        startActivityForResult(intent, REQUEST_CODE_SELECT);
    }

    /**
     * 跳转回调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null && requestCode == REQUEST_CODE_EDIT) {

            switch (data.getStringExtra("type")) {
                case "trueName": // 真实姓名
                    saveExpertInfoBase(editExpert("trueName", data.getStringExtra("edit")));
                    break;
                case "titleNumber": // 专家职称号
                    saveExpertInfoBase(editExpert("titleNumber", data.getStringExtra("edit")));
                    break;
                case "company": // 工作单位
                    saveExpertInfoBase(editExpert("otherAddress", data.getStringExtra("edit")));
                    break;
                case "addressDetail": // 详细地址
                    saveExpertInfoBase(editExpert("addressDetail", data.getStringExtra("edit")));
                    break;
                case "achievement": // 个人成就
                    saveExpertInfoBase(editExpert("achievement", data.getStringExtra("edit")));
                    break;
                case "intro": // 个人简介
                    saveExpertInfoBase(editExpert("expertIntroduce", data.getStringExtra("edit")));
                    break;
                case "area": // 领域说明
                    expertAreaTypeCode = data.getStringExtra("expertAreaTypeCode");
                    expertAreaDirectionCode = data.getStringExtra("expertAreaDirectionCode");
                    saveExpertInfoBase(editArea("area", data.getStringExtra("tvExpertArea")));
                    break;
            }

        } else if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                showDialog("上传中,请稍候!");
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                filePath = images.get(0).path;
                selectedImageList.addAll(images);
                BusinessFile.imageCompressAndUpload(AccountExpertManagementActivity.this, filePath, mHandler);
            }
        }
    }

    /**
     * 所在区域选择
     */
    private void showAddressPicker() {
        final BottomDialog bottomDialog = new BottomDialog(AccountExpertManagementActivity.this);
        bottomDialog.setOnAddressSelectedListener(new OnAddressSelectedListener() {
            @Override
            public void onAddressSelected(Province province, City city, County county, Street street) {
                provinceCode = province.province_code;
                cityCode = city != null ? city.city_code : "";
                countyCode = county != null ? county.county_code : "";
                saveExpertInfoBase(editAddress("address", String.format("%s %s %s", province.province_name,
                        city != null ? city.city_name : "", county != null ? county.county_name : "")));
                bottomDialog.dismiss();
            }
        });
        bottomDialog.show();
    }

    /**
     * 跳转到编辑页面
     *
     * @param type 标记修改的类型
     */
    private void gotoEditActivity(String type, String content) {
        if (cannotModify()) return;
        Intent intent = new Intent(AccountExpertManagementActivity.this, EditExpertInfoActivity.class);
        intent.putExtra("type", type);
        intent.putExtra("content", content);
        startActivityForResult(intent, REQUEST_CODE_EDIT);
    }

    /**
     * 判断是否可以修改
     *
     * @return
     */
    private boolean cannotModify() {
        if (ExpertInfoXML.getIsAudit(this).equals("2")) {
            CustomDialog.nativeDialog(this, "正在审核中，无法修改！");
            dismissDialog();
            return true;
        }
        return false;
    }

    @OnClick({R.id.rl_expert_avatar, R.id.rl_expert_true_name, R.id.rl_expert_sex, R.id.rl_expert_company, R.id.rl_expert_company_other, R.id.rl_expert_title, R.id.rl_expert_address, R.id.rl_expert_address_detail,
            R.id.rl_expert_achievement, R.id.rl_expert_intro, R.id.rl_expert_area, R.id.rl_expert_authentication, R.id.rl_expert_mobile_phone, R.id.rl_expert_update_pwd, R.id.btn_expert_login_out, R.id.rl_expert_title_number,
            R.id.rl_expert_title_photo, R.id.rl_expert_birthday,R.id.rl_pay_pwd,R.id.rl_auth_login})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_expert_avatar:  // 头像
                if (cannotModify()) return;
                selectImage(0);
                break;
            case R.id.rl_expert_true_name: // 真实姓名
                gotoEditActivity("trueName", ExpertInfoXML.getExpertName(AccountExpertManagementActivity.this));
                break;
            case R.id.rl_expert_sex: // 性别
                if (cannotModify()) return;
                pvSex.show();
                break;
            case R.id.rl_expert_birthday: // 生日
                showDatePicker();
                break;
            case R.id.rl_expert_company: // 工作单位选择
                if (cannotModify()) return;
                if (pvOrganization != null)
                    pvOrganization.show();
//                gotoEditActivity("company", ExpertInfoXML.getWorkUnit(AccountExpertManagementActivity.this));
                break;
            case R.id.rl_expert_company_other: // 工作单位填写
                if (cannotModify()) return;
                gotoEditActivity("company", ExpertInfoXML.getOtherAddress(AccountExpertManagementActivity.this));
                break;
            case R.id.rl_expert_address: // 工作地址
                if (cannotModify()) return;
                showAddressPicker();
                break;
            case R.id.rl_expert_address_detail: // 详细地址
                gotoEditActivity("addressDetail", ExpertInfoXML.getAddressDetail(AccountExpertManagementActivity.this));
                break;
            case R.id.rl_expert_achievement: // 个人成就
                gotoEditActivity("achievement", ExpertInfoXML.getAchievement(AccountExpertManagementActivity.this));
                break;
            case R.id.rl_expert_intro: // 个人简介
                gotoEditActivity("intro", ExpertInfoXML.getExpertIntroduce(AccountExpertManagementActivity.this));
                break;
            case R.id.rl_expert_area: // 专业领域
                if (cannotModify()) return;
                Intent intent = new Intent(AccountExpertManagementActivity.this, ExpertInfoAreaActivity.class);
                startActivityForResult(intent, REQUEST_CODE_EDIT);
                break;
            case R.id.rl_expert_authentication: // 认证信息
                if (ExpertInfoXML.getIsAudit(this).equals("0")) {
                    CustomDialog.nativeDialog(this, "审核未通过，请查看审核状态！");
                    return;
                }

                if (ExpertInfoXML.getIsAudit(this).equals("2") || ExpertInfoXML.getIsChangeAudit(this).equals("2")) {
                    CustomDialog.nativeDialog(this, "正在审核中，无法修改！");
                    return;
                }
                GotoUtil.gotoActivity(AccountExpertManagementActivity.this, AuthenticationInfoActivity.class);
                break;
            case R.id.rl_expert_mobile_phone: // 绑定手机
                GotoUtil.gotoActivity(AccountExpertManagementActivity.this, MobilePhoneIdentificationStepOneActivity.class);
                break;
            case R.id.rl_expert_update_pwd: // 修改密码
                GotoUtil.gotoActivity(AccountExpertManagementActivity.this, UpdatePasswordActivity.class);
                break;
            case R.id.rl_expert_title_number: // 专家职称号
                gotoEditActivity("titleNumber", ExpertInfoXML.getExpertTitleNum(AccountExpertManagementActivity.this));
                break;
            case R.id.rl_expert_title_photo: // 专家职称照片
                if (cannotModify()) return;
                selectImage(1);
                break;
            case R.id.rl_expert_title: // 专家职称
                if (cannotModify()) return;
                getExpertTitle();
                break;
            case R.id.rl_pay_pwd: // 设置支付密码
                BusinessPayPassword.havePayPassword(this, mHandler);
                break;
            case R.id.rl_auth_login: // 第三方授权登陆
                GotoUtil.gotoActivity(AccountExpertManagementActivity.this, AuthLoginListActivity.class);
                break;
            case R.id.btn_expert_login_out: // 退出登录
                new MaterialDialog.Builder(AccountExpertManagementActivity.this)
                        .title("提示")
                        .content("您确定要退出登录吗？")
                        .positiveText("确定")
                        .negativeText("取消")
                        .onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                SharedPreferencesUtil.cleanXml(AccountExpertManagementActivity.this, UserXML.XML_NAME_USER);
                                SharedPreferencesUtil.cleanXml(AccountExpertManagementActivity.this, PersonalInfoXML.XML_NAME_PERSONAL_INFO);
                                SharedPreferencesUtil.cleanXml(AccountExpertManagementActivity.this, RongCloudXML.XML_NAME_RONG);
                                SharedPreferencesUtil.cleanXml(AccountExpertManagementActivity.this, ExpertInfoXML.XML_NAME_EXPERT_INFO);
                                SharedPreferencesUtil.cleanXml(AccountExpertManagementActivity.this, ChannelXML.XML_NAME_CHANNEL);
                                clearJPushAlias();
//                                finish();
                                ActivityTaskManager.getInstance().closeAllActivity();
                                GotoUtil.gotoActivity(AccountExpertManagementActivity.this, LoginActivity.class, "logout", "");
                            }
                        })
                        .show();
                break;
        }
    }

    /**
     * 显示日期选择
     */
    private void showDatePicker() {

        Calendar calendar = Calendar.getInstance();
        mYear = calendar.get(Calendar.YEAR);
        mMonth = calendar.get(Calendar.MONTH);
        mDayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);

        DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int year, int month, int dayOfMonth) {
                String selectDate = year + "-" + (month + 1) + "-" + dayOfMonth;
                saveExpertInfoBase(editExpert("birthday", selectDate));
//                tvExpertBirthday.setText(selectDate);
            }
        }, mYear, mMonth, mDayOfMonth);

        datePickerDialog.getDatePicker().setMaxDate(System.currentTimeMillis() - 1000);
        datePickerDialog.show();
    }

    /**
     * 取消极光别名设置
     */
    private void clearJPushAlias() {
        JPushInterface.setAlias(this, "", new TagAliasCallback() {
            @Override
            public void gotResult(int code, String s, Set<String> set) {
                if (code == 0) { // 成功
                    LogUtils.e("JPush alias cancel success");
                } else if (code == 6002) { // 超时
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            JPushInterface.setAlias(AccountExpertManagementActivity.this, "", null);
                        }
                    }, 1000 * 60);
                } else { // 失败
                    LogUtils.e("Failed with errorCode = " + code);
                }
            }
        });
    }

    /**
     * 获取专家职称
     */
    private void getExpertTitle() {
        if (expertTitleVOList.size() <= 0) {
            BusinessExpert.expertTitleList(this, mHandler);
        } else
            pvExpertTitle.show();
    }
}
